<?php
namespace app\manage\controller;
use my\MyRedis;
use think\Db;
use think\Queue;
use app\job\OrderClose;

class Test extends Base
{

    public function index() {
//        $this->setRedisRoleData();
//        exit('SUCCESS');

//        $redis = MyRedis::getInstance(['select'=>1]);
//        $count = $redis::lLen('message');
//        $pageSize = 50;
//        $res = $redis::lRange('message',$count-$pageSize,$count-1);
//        $list = [];
//        foreach ($res as $v) {
//            $json = json_decode($v,true);
//            $list[] = $json;
//        }
//        halt($list);
    }

    private function setRedisRoleData() {
        $redis = MyRedis::getInstance();
        $where = [
            ['del','=',0],
            ['status','=',1]
        ];
        $rolelist = Db::table('mp_auth_role')->where($where)->field('id,title,status,rules_content,route,route_content')->order(['id'=>'ASC'])->select();
        foreach ($rolelist as $role) {
            $rules = explode(',',$role['rules_content']);
            foreach ($rules as &$name) {
                $name = strtolower($name);
            }
            $data['status'] = $role['status'];
            $data['rules'] = $rules;
            $redis::set('role' . $role['id'],json_encode($data));
            $redis::set('route' . $role['id'],$role['route_content']);
            if($role['route']) {
                $redis::set('route' . $role['id'],$role['route_content']);
            }
        }

        $routeList = Db::table('mp_menu')->field('id,title,path,icon,pid')->order(['sort'=>'DESC','id'=>'ASC'])->select();
        $new_arr = [];
        foreach ($routeList as $route) {
            if($route['pid'] === 0) {
                $subs = [];
                foreach ($routeList as $v) {
                    if($route['id'] == $v['pid']) {
                        $subs[] = $v;
                    }
                }
                $route['subs'] = $subs;
                $new_arr[] = $route;
            }
        }
        $route_content = json_encode($new_arr);
        $redis::set('routeroot',$route_content);

    }


    public function sendMsg() {
        $message = input('param.msg',date('Y-m-d H:i:s'));
        $event = "chat message";
        $array = [
            'fromId' => '6',
            'msg' => $message,
            'toId' => '',
            'toUid' => '1',
        ];
        $res = $this->emit($event,$array);
        halt($res);
    }

    private function historyMessage()
    {
        $myId = $this->userinfo['admin_id'];
        $redis = MyRedis::getInstance(['select'=>1]);
        $count = $redis::lLen('message');
        $pageSize = 50;
        $res = $redis::lRange('message',$count-$pageSize,$count-1);
        $list = [];
        foreach ($res as $v) {
            $json = json_decode($v,true);
            if($json['message']['toUid']) {
                //私聊
                if($json['message']['toUid'] === $myId || $json['message']['fromId']) {
                    $list[] = $json;
                }
            }else {
                //群发
                $list[] = $json;
            }
        }
        return ajax($list);
//        $event = "chat message";
//        $message = date('Y-m-d H:i:s');
//        $array = [
//            'username' => '姜海蕤',
//            'age' => 30
//        ];
//        $res = $this->emit($event,$array);
//        halt($res);
    }

    public function articleAdd() {
        $arr = [
            ['title' => '三国演义', 'author' => '罗贯中', 'desc' => '四大名著'],
            ['title' => '红楼梦', 'author' => '曹雪芹', 'desc' => '四大名著'],
            ['title' => '水浒传', 'author' => '施耐庵', 'desc' => '四大名著'],
            ['title' => '西游记', 'author' => '吴承恩', 'desc' => '四大名著'],
            ['title' => '论语', 'author' => '孔丘', 'desc' => ''],
            ['title' => '物种起源', 'author' => '达尔文', 'desc' => ''],
            ['title' => '君主论', 'author' => '尼可罗·马基亚维利', 'desc' => ''],
            ['title' => '孙子兵法', 'author' => '孙武', 'desc' => ''],
            ['title' => '史记', 'author' => '司马迁', 'desc' => ''],
            ['title' => '曾国藩家书', 'author' => '曾国藩', 'desc' => ''],
            ['title' => '悲惨世界', 'author' => '雨果', 'desc' => ''],
            ['title' => '百年孤独', 'author' => '加夫列尔·加西亚·马尔克斯', 'desc' => ''],
            ['title' => '老人与海', 'author' => '海明威', 'desc' => ''],
            ['title' => '钢铁是怎样炼成的', 'author' => '尼·奥斯特洛夫斯基', 'desc' => ''],
            ['title' => '堂吉诃德', 'author' => '塞万提斯', 'desc' => ''],
            ['title' => '茶花女', 'author' => '亚历山大.小仲马', 'desc' => ''],
            ['title' => '罪与罚', 'author' => '陀思妥耶夫斯基', 'desc' => ''],
            ['title' => '麦田里的守望者', 'author' => '塞林格', 'desc' => ''],
            ['title' => '活着', 'author' => '余华', 'desc' => ''],
            ['title' => '朝花夕拾', 'author' => '鲁迅', 'desc' => ''],
            ['title' => '猎人笔记', 'author' => '屠格涅夫', 'desc' => ''],
            ['title' => '镜花缘', 'author' => '李汝珍', 'desc' => ''],
            ['title' => '湘行散记', 'author' => '沈从文', 'desc' => ''],
            ['title' => '骆驼祥子', 'author' => '老舍', 'desc' => ''],
            ['title' => '海底两万里', 'author' => '凡尔纳', 'desc' => ''],
            ['title' => '红岩', 'author' => '罗广斌、杨益言', 'desc' => ''],
            ['title' => '哈利·波特与死亡圣器', 'author' => 'JK罗琳', 'desc' => ''],
            ['title' => '红星照耀中国', 'author' => '埃德加·斯诺', 'desc' => ''],
            ['title' => '昆虫记', 'author' => '法布尔', 'desc' => ''],
            ['title' => '飞向太空港', 'author' => '李鸣生', 'desc' => ''],
            ['title' => '长征', 'author' => '王树增', 'desc' => ''],
            ['title' => '星星离我们有多远', 'author' => '卞毓麟', 'desc' => ''],
            ['title' => '寂静的春天', 'author' => '蕾切尔·卡森', 'desc' => ''],
            ['title' => '傅雷家书', 'author' => '傅雷', 'desc' => ''],
            ['title' => '钢铁是怎样炼成的', 'author' => '奥斯特洛夫斯基', 'desc' => ''],
            ['title' => '苏菲的世界', 'author' => '乔斯坦·贾德', 'desc' => ''],
            ['title' => '给青年的十二封信', 'author' => '朱光潜', 'desc' => ''],
            ['title' => '平凡的世界', 'author' => '路遥', 'desc' => ''],
            ['title' => '名人传', 'author' => '罗曼·罗兰', 'desc' => ''],
            ['title' => '泰戈尔诗选', 'author' => '泰戈尔', 'desc' => ''],
            ['title' => '聊斋志异', 'author' => '蒲松龄', 'desc' => ''],
            ['title' => '儒林外史', 'author' => '吴敬梓', 'desc' => ''],
        ];
        $insert_Data = $arr[mt_rand(0,(count($arr)-1))];
        $insert_Data['sex'] = mt_rand(0,1);
        $insert_Data['age'] = mt_rand(28,80);
        try {
            $res1 = Db::table('test')->insert($insert_Data);
//            $res2 = Db::table('test')->where([])->order(['id'=>'DESC'])->limit(0,5)->select();
        } catch (\Exception $e) {
            return ajax('',-1,$e->getMessage());
        }
//        return ajax();
        halt([$res1]);
    }

    public function articleDelete()
    {
        try {
            $where = [];
            $exist = Db::table('test')->where($where)->find();
            if(!$exist) {
                die('没有数据了');
            }else {
                $where[] = ['id','=',$exist['id']];
                $res = Db::table('test')->where($where)->delete();
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(), -1);
        }
        dump($res);
        halt($exist);
    }

    protected function getip() {
        $unknown = 'unknown';
        if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        /*
        处理多层代理的情况
        或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
        */
        if (false !== strpos($ip, ',')) {
            $ip_arr = explode(',', $ip);
            $ip = reset($ip_arr);
        }
        return $ip;
    }

    private function orderClose() {
        $where = [
            ['status','=',0],
            ['del','=',0],
            ['create_time','<',time() - 3600]
        ];
        $list = Db::table('mp_food_order')->where($where)->select();
        foreach ($list as $o) {

            Queue::later(1,OrderClose::class,['order_id'=>$o['id']],'orderClose');
        }
        halt($list);
    }

    private function queuetest() {
        $queue = null;  //第三个参数选填,默认queue:default

        $data = ['order_id'=>create_unique_number('o')];
        /*--- 立即执行 ---*/
        Queue::push('Message@sendSms',$data);
        /*--- 延迟执行 ---*/
        Queue::later(5,OrderClose::class,$data,'orderClose');
        exit('succes');
    }

    private function sockettest()
    {
        halt($_SERVER);
        $event = "food_order";
        $array = [
            'order_id' => 1,
            'shop_name' => '老友部落酸菜鱼(灵泉北里店)',
            'number' => 30,
            'pay_price' => 95,
            'pay_time' => time(),
            'pay_order_sn' => create_unique_number(''),
            'desc' => '不要筷子!绿色环保!',
            'detail' => [
                [
                    'food_name' => '麻辣小龙虾 (蒜香)',
                    'num' => 2,
                    'total_price' => 13.5,
                ],
                [
                    'food_name' => '川味回锅肉盖饭',
                    'num' => 1,
                    'total_price' => 21.84,
                ],
                [
                    'food_name' => '重庆鸡公煲+配菜+米饭+饮料',
                    'num' => 2,
                    'total_price' => 46.00,
                ],
            ]
        ];
        $res = $this->emit($event,$array);
        halt($res);
    }

    private function emit($event ,$message) {
        $data = [$event,$message];
        $object = json_decode('{}');
        $array = [
            "emitter",
            [
                'type' => 2,
                'data' => $data,
                'nsp' => '/'
            ],
            [
                'rooms' => [],
                'flags' => $object,
                'except' => []
            ],
        ];
        $publish_data = msgpack_pack($array);
        $redis = MyRedis::getInstance();
        $res = $redis::publish('socket.io#/#',$publish_data);
        return $res;
    }







}